package com.xuecheng.teaching.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.WorkRecordCorrectionStatusEnum;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.WorkCorrectDto;
import com.xuecheng.commons.model.dto.WorkRecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.system.api.SystemClient;
import com.xuecheng.teaching.domain.CourseWorkRec;
import com.xuecheng.teaching.domain.Work;
import com.xuecheng.teaching.domain.WorkRecord;
import com.xuecheng.teaching.mapper.WorkRecordMapper;
import com.xuecheng.teaching.service.CourseWorkRecService;
import com.xuecheng.teaching.service.WorkRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.teaching.service.WorkService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 作业提交记录 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-18
 */
@Service
public class WorkRecordServiceImpl extends ServiceImpl<WorkRecordMapper, WorkRecord> implements WorkRecordService {

    @Autowired
    private SystemClient systemClient;//用户feign

    @Autowired
    private WorkService workService;//作业

    @Autowired
    private ContentClient contentClient;//课程feign

    //提交答案
    @Override
    public ResponseResult submitAnswer(WorkRecordDto workRecordDto) {
        //前端参数校验
        if (workRecordDto==null){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //dto转数据库实体
        WorkRecord workRecord = BeanHelper.copyProperties(workRecordDto, WorkRecord.class);
        //获取用户
        ResponseResult<UserVo> responseResult = systemClient.getUserById(AuthInfoHolder.getUserId());
        if (responseResult.getCode()!=0){
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //取出用户
        UserVo userVo = responseResult.getData();
        //根据workId获取作业
        Work work = workService.getById(workRecordDto.getWorkId());
        //补全信息
        workRecord.setUserId(userVo.getId());//提交人id
        workRecord.setUsername(userVo.getName());//提交人名字
        workRecord.setQuestion(work.getQuestion());//问题题目
        workRecord.setStatus(WorkRecordCorrectionStatusEnum.RECORD_CORRECT_PENDING.getCode());//待批改
        workRecord.setCreateDate(new Date());//创建时间
        workRecord.setCompanyId(1217339321501278210L);
        //写入作业记录表
        this.save(workRecord);
        //返回
        return ResponseResult.okResult();
    }

    @Autowired
    private CourseWorkRecService courseWorkRecService;

    //分页+条件查询
    @Override
    public ResponseResult<WorkRecordVo> findByPage(PageRequest pageRequest, String courseName) {
        //courseName json转字符串
        WorkRecordVo jsonObject = JSON.parseObject(courseName, WorkRecordVo.class);
        String courseName_Str = jsonObject.getCourseName();
        //构建分页
        Page<WorkRecord> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //开启分页
        if (StrUtil.isNotBlank(courseName_Str)){
            ResponseResult<List<Long>> responseResult = contentClient.findIdByName(courseName_Str);
            if (responseResult.getCode()!=0){
                throw new BusinessException(ErrorCode.DATAERROR);
            }
            //取出id列表
            List<Long> coursePubIdLIst = responseResult.getData();
            boolean selectFlag = CollectionUtil.isNotEmpty(coursePubIdLIst);
            if (selectFlag==true){
                page = this.lambdaQuery().select(WorkRecord::getCoursePubId).in(WorkRecord::getCoursePubId,coursePubIdLIst).groupBy(WorkRecord::getCoursePubId).page(page);
            }else {
                page = this.lambdaQuery().select(WorkRecord::getCoursePubId).groupBy(WorkRecord::getCoursePubId).page(page);
            }
        }else {
            page = this.lambdaQuery().select(WorkRecord::getCoursePubId).groupBy(WorkRecord::getCoursePubId).page(page);
        }
        //获取数据库记录
        List<WorkRecord> recordList = page.getRecords();
        //封装结果集
        List<WorkRecordVo> workRecordVoList =new ArrayList<>();
        for (WorkRecord workRecord : recordList) {
            ResponseResult<CoursePubVo> responseResult = contentClient.findById(workRecord.getCoursePubId());
            if (responseResult.getCode()!=0){
                throw new BusinessException(ErrorCode.DATAERROR);
            }
            //获取课程发布对象
            CoursePubVo coursePubVo = responseResult.getData();
            //获取vo
            WorkRecordVo workRecordVo = getWorkRecordVo(coursePubVo);
            //写入课程作业数据库
            writeCourseWorkRec(workRecordVo);
            //添加集合
            workRecordVoList.add(workRecordVo);
        }
        return PageResponseResult.okResult(page.getTotal(),workRecordVoList);
    }

    //分页查询提交的作业
    @Override
    public ResponseResult<WorkCorrectVo> workPage(PageRequest pageRequest, Long teachplanId) {
        //构建分页
        Page<WorkRecord> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //开启分页
        page = this.lambdaQuery().eq(WorkRecord::getTeachplanId,teachplanId).page(page);
        //获取分页结果
        List<WorkRecord> recordList = page.getRecords();
        //声明结果集
        List<WorkCorrectVo> workCorrectVoList=new ArrayList<>();
        for (WorkRecord workRecord : recordList) {
            WorkCorrectVo workCorrectVo = new WorkCorrectVo();
            workCorrectVo = BeanHelper.copyProperties(workRecord,WorkCorrectVo.class);
            workCorrectVo.setWorkRecordId(workRecord.getId());//设置主键
            workCorrectVoList.add(workCorrectVo);
        }
        //返回
        return PageResponseResult.okResult(page.getTotal(),workCorrectVoList);
    }

    //批改作业
    @Override
    public ResponseResult correctWork(WorkCorrectDto workCorrectDto) {
        //构造修改实体
        WorkRecord workRecord = new WorkRecord();
        //补全信息
        workRecord.setId(workCorrectDto.getWorkRecordId());//设置id
        workRecord.setCorrectComment(workCorrectDto.getCorrectComment());//评语
        workRecord.setStatus(WorkRecordCorrectionStatusEnum.RECORD_CORRECT_PENDED.getCode());//设置状态 已批改
        workRecord.setTeacherId(AuthInfoHolder.getUserId());//批改人
        workRecord.setCorrectionDate(new Date());//批改时间
        //修改数据库
        this.updateById(workRecord);
        return ResponseResult.okResult();
    }

    //获取课程内包含的作业数
    @Override
    public ResponseResult<Integer> getGroupNum(Long coursePubId) {
        Integer groupNum = workRecordMapper.groupNum(coursePubId);
        return ResponseResult.okResult(groupNum);
    }

    //写入课程作业数据库
    private void writeCourseWorkRec(WorkRecordVo workRecordVo) {
        CourseWorkRec courseWorkRec = new CourseWorkRec();
        CourseWorkRec courseWorkRec_data = courseWorkRecService.lambdaQuery().eq(CourseWorkRec::getCoursePubId, workRecordVo.getCoursePubId()).one();
        if (courseWorkRec_data!=null){
            courseWorkRec.setId(courseWorkRec_data.getId());//设置主键
        }
        courseWorkRec.setCoursePubId(workRecordVo.getCoursePubId());//课程发布id
        courseWorkRec.setCourseName(workRecordVo.getCourseName());//课程名
        courseWorkRec.setWorkNumber(workRecordVo.getWorkNumber() * workRecordVo.getTotalUsers());//作业总数
        courseWorkRec.setAnswerNumber(workRecordVo.getTotalUsers());//答题人数
        courseWorkRec.setTobeReviewed(workRecordVo.getTobeReviewed());//待批阅人数
        courseWorkRec.setCommitedTime(DateUtil.parse(workRecordVo.getCommitedTime()));//最后提交时间
        if (workRecordVo.getReviewedTime()!=null){
            courseWorkRec.setReviewedTime(DateUtil.parse(workRecordVo.getReviewedTime()));//最后批阅时间
        }
        courseWorkRec.setCreateDate(new Date());
        //写入数据库
        courseWorkRecService.saveOrUpdate(courseWorkRec);
    }

    @Autowired
    private WorkRecordMapper workRecordMapper;

    //处理vo
    private WorkRecordVo getWorkRecordVo(CoursePubVo coursePubVo) {
        WorkRecordVo workRecordVo = new WorkRecordVo();
        workRecordVo.setCourseName(coursePubVo.getName());//课程名称
        workRecordVo.setCoursePubId(coursePubVo.getId());//课程发布id
        workRecordVo.setCompanyName(coursePubVo.getCompanyName());//机构名称
        Integer workNum = workRecordMapper.groupNum(coursePubVo.getId());
        workRecordVo.setWorkNumber(workNum);//课程内的作业数 TODO
        Long countTotalUser = this.lambdaQuery().eq(WorkRecord::getCoursePubId, coursePubVo.getId()).count();
        workRecordVo.setTotalUsers(countTotalUser.intValue());//答题人数
        Long countTobeReviewed = this.lambdaQuery().eq(WorkRecord::getCoursePubId, coursePubVo.getId()).eq(WorkRecord::getStatus, WorkRecordCorrectionStatusEnum.RECORD_CORRECT_PENDING.getCode()).count();
        workRecordVo.setTobeReviewed(countTobeReviewed.intValue());//待批阅人数
        Long countReviewed = this.lambdaQuery().eq(WorkRecord::getCoursePubId, coursePubVo.getId()).eq(WorkRecord::getStatus, WorkRecordCorrectionStatusEnum.RECORD_CORRECT_PENDED.getCode()).count();
        workRecordVo.setReviewed(countReviewed.intValue());//已批阅数
        WorkRecord workLastCommit = this.lambdaQuery().eq(WorkRecord::getCoursePubId, coursePubVo.getId()).orderByDesc(WorkRecord::getCreateDate).list().get(0);
        workRecordVo.setCommitedTime(workLastCommit.getCreateDate().toString());//最后提交时间
        WorkRecord workLastReview = this.lambdaQuery().eq(WorkRecord::getCoursePubId, coursePubVo.getId()).orderByDesc(WorkRecord::getCorrectionDate).list().get(0);
        if (workLastReview.getCorrectionDate()!=null){
            workRecordVo.setReviewedTime(workLastReview.getCorrectionDate().toString());//最后批阅时间
        }
        return workRecordVo;
    }
}
